'use strict';

const Service = require('egg').Service;
const md5 = require('md5')
class AdminService extends Service{
    async isadmin(username){
       try {
            const {ctx} = this;
            if(!username) throw '没有账号';
            let result = await ctx.model.Admin.findOne({username}).exec();
            if(result){
                return {data:2,content:'已被注册'};
            }else{
                return {data:1,content:'暂未注册'};
            }
       } catch (error) {
           return {data:0,content:error};
       }
    }
    async login(username,password){
        try {
             const {ctx} = this;
             if(!username && !password)return;
             password = md5(md5(password).substr(4,6) + md5(password));
             let count = await ctx.model.Admin.count({username});
             if(count==0){
                return {data:2,content:'账号不存在'};
             }
             let result = await ctx.model.Admin.findOne({username,password}).exec();
             if(result){
                 let {nickName,role,_id,openid} = result;
                 ctx.session.role = result.role;
                 ctx.session.admin = {username,nickName,role,_id,openid};
                 ctx.session.islogin = true;
                 result.password = null;
                 return {data:1, result};
             }else{
                 return {data:3,content:'密码输入有误'};
             }
        } catch (error) {
            console.log(error)
            return {data:0,content:error};
        }
     }
}
module.exports = AdminService;